
#############
##改修履歴
#############

#2014/11/12 全体を最初に出力


outf <- function(obj, file, sep="\t") {
    cat(obj, file=file, sep=sep)
    cat("\n", file=file)
}


setwd("/var/www/html/total/app/data/")

#引数
args <- commandArgs(trailingOnly=TRUE)

labelf <- args[1]
rawf <- args[2]
#出力ファイル名
ofile <- paste("gt", args[3], sep="")

isN<-isP<-FALSE
#集計表タイプ(N、P、NP)

if (args[4] == "N") {
    isN <- TRUE
} else if(args[4] == "P") {
    isP <- TRUE
} else {
    isN <- isP <- TRUE
}


#rawf <- "rawdata-utf8.csv"
#labelf <- "label-utf8.csv"
#ofile <- "gt.txt"

labels <- read.csv(labelf, header=TRUE)
raws <- read.csv(rawf, header=TRUE)

output <- file(ofile, open="w")

for ( i in 1:nrow(labels) ) {
    
    cate <- NULL
    tn <- NULL
    tp <- NULL

    label <- labels[i,]

    #サンプルNo列（設問タイプが空）とFAが対象外
    if (is.na(label$t) || label$t == "" || label$t == "FA") {
    
    } else {
        #空行を出力
        cat("\n", file=output)

        print(paste(label$la, label$nm, sep="\t"));
        outf(paste(label$la, label$nm, sep="\t"), file=output)

        cate <- label[9:length(label)]
        cate <- cate[cate != ""]
    }
    
    if (label$t == "SA") {

        #無回答を含む
        tn <- table(raws[,label$cno], exclude=NULL);

        #tn <- addmargins(tn)
        tn <- c(nrow(raws), tn)
        names(tn) <- c("全体", cate, "<無回答>")
        
        tp <- tn/tn[1]*100

        print(tn);
        outf(names(tn), file=output)
        
        if (isN) {
            outf(tn, file=output)
        }

        print(tp);
        if (isP) {
            outf(tp, file=output)
        }

    } else if (label$t == "MA") {

        for (j in label$cno:label$cno2) {
            col <- subset(raws, raws[,j] == 1,c(j))
            tn <- c(tn, nrow(col))
        }
        #無回答
        colna <- subset(raws, is.na(raws[,label$cno]), c(label$cno))
        tn <- array(c(tn, nrow(colna)))

        #合計
        tn <- c(nrow(raws), tn)
        names(tn) <- c("全体", cate, "<無回答>")
        
        #MAの%は手動計算が必要
        tp <- tn/tn[1]*100

        print(tn)
        outf(names(tn), file=output)
        if (isN) {
            outf(tn, file=output)
        }

        print(tp);
        if (isP) {
            outf(tp, file=output)
        }

    } else if (label$t == "NU") {
        min <- min(raws[,label$cno])
        max <- max(raws[,label$cno])
        mean <- mean(raws[,label$cno])
        median <- median(raws[,label$cno])
        sum <- sum(raws[,label$cno])
        sd <- sd(raws[,label$cno])

        tn <- c(nrow(raws), min, max, mean, median, sum, sd)
        names(tn) <- c("全体", "最小", "最大", "平均", "中央", "合計", "標準偏差")
        print(tn);
        outf(names(tn), file=output)
        outf(tn, file=output)

    }

}

close(output)
